'use client';

import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

interface User {
  openId: string;
  uName: string;
  avatarUrl: string;
  college: string | null;
  gender: string | null;
  birth: string | null;
}

interface UserDialogProps {
  user: User | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: (user: User) => void;
}

export function UserDialog({ user, open, onOpenChange, onSave }: UserDialogProps) {
  const [editedUser, setEditedUser] = useState<User | null>(null);

  useEffect(() => {
    if (user) {
      setEditedUser(user);
    }
  }, [user]);

  if (!user || !editedUser) return null;

  const handleSave = async () => {
    try {
      const response = await fetch(`/api/users/${user.openId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(editedUser),
      });

      if (!response.ok) {
        throw new Error('更新用户信息失败');
      }

      onSave(editedUser);
      onOpenChange(false);
    } catch (error) {
      console.error('更新用户信息失败:', error);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>用户详情</DialogTitle>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-4 items-center gap-4">
            <img
              src={editedUser.avatarUrl}
              alt={editedUser.uName}
              className="h-12 w-12 rounded-full col-span-1"
            />
            <div className="col-span-3">
              <Input
                value={editedUser.uName}
                onChange={(e) => setEditedUser({ ...editedUser, uName: e.target.value })}
                placeholder="用户名"
              />
            </div>
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">学院</label>
            <Input
              className="col-span-3"
              value={editedUser.college || ''}
              onChange={(e) => setEditedUser({ ...editedUser, college: e.target.value })}
              placeholder="请输入学院"
            />
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">性别</label>
            <Select
              value={editedUser.gender || ''}
              onValueChange={(value) => setEditedUser({ ...editedUser, gender: value })}
            >
              <SelectTrigger className="col-span-3">
                <SelectValue placeholder="请选择性别" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="男">男</SelectItem>
                <SelectItem value="女">女</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">生日</label>
            <Input
              className="col-span-3"
              type="date"
              value={editedUser.birth || ''}
              onChange={(e) => setEditedUser({ ...editedUser, birth: e.target.value })}
            />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
          <Button onClick={handleSave}>保存</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}